// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#pragma once

#include <pollux/exec/operator.h>
#include <pollux/exec/operator_utils.h>

namespace kumo::pollux::exec {
    class CallbackSink : public Operator {
    public:
        CallbackSink(
            int32_t operatorId,
            DriverCtx *driverCtx,
            std::function<BlockingReason(RowVectorPtr, ContinueFuture *)> callback)
            : Operator(driverCtx, nullptr, operatorId, "N/A", "CallbackSink"),
              callback_{std::move(callback)} {
        }

        void addInput(RowVectorPtr input) override {
            loadColumns(input, *operatorCtx_->execCtx());
            blockingReason_ = callback_(std::move(input), &future_);
        }

        RowVectorPtr getOutput() override {
            return nullptr;
        }

        bool needsInput() const override {
            return callback_ != nullptr;
        }

        void noMoreInput() override {
            Operator::noMoreInput();
            close();
        }

        BlockingReason isBlocked(ContinueFuture *future) override {
            if (blockingReason_ != BlockingReason::kNotBlocked) {
                *future = std::move(future_);
                blockingReason_ = BlockingReason::kNotBlocked;
                return BlockingReason::kWaitForConsumer;
            }
            return BlockingReason::kNotBlocked;
        }

        bool isFinished() override {
            return noMoreInput_;
        }

    private:
        void close() override {
            if (callback_) {
                callback_(nullptr, nullptr);
                callback_ = nullptr;
            }
        }

        ContinueFuture future_;
        BlockingReason blockingReason_{BlockingReason::kNotBlocked};
        std::function<BlockingReason(RowVectorPtr, ContinueFuture *)> callback_;
    };
} // namespace kumo::pollux::exec
